import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

// class WeChatRobot2 {
//   final String key='6072ed81-7294-48b5-a017-fc990e2ff40e';
//   //final String webhookUrl='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6072ed81-7294-48b5-a017-fc990e2ff40e';

 

//   /// 发送文本消息
//   Future<void> sendTextMessage(String content) async {
//     final Map<String, dynamic> message = {
//       "msgtype": "text",
//       "text": {
//         "content": content,
//       },
//     };

//     final response = await http.post(
//       Uri.parse(webhookUrl),
//       headers: {"Content-Type": "application/json"},
//       body: jsonEncode(message),
//     );

//     if (response.statusCode == 200) {
//       print("消息发送成功: ${response.body}");
//     } else {
//       print("消息发送失败: ${response.statusCode}, ${response.body}");
//     }
//   }
// /// 发送文件到企业微信
//   Future<bool> sendFile(String mediaId, String webhookUrl) async {
//   final url = Uri.parse(webhookUrl);
//   final headers = {'Content-Type': 'application/json'};
//   final body = json.encode({
//     "msgtype": "file",
//     "file": {"media_id": mediaId}
//   });

//   try {
//     var response = await http.post(url, headers: headers, body: body);
//     return response.statusCode == 200;
//   } catch (e) {
//     return false;
//   }
// }
// ///上传文件到企业微信
//   Future<String> uploadFile(String filePath) async {
//     final uploadUrl = Uri.parse(
//       'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=$webhookUrl&type=file'
//     );

//     var request = http.MultipartRequest('POST', uploadUrl);
//     request.files.add(await http.MultipartFile.fromPath('media', filePath));

//     try {
//       var response = await request.send();
//       if (response.statusCode == 200) {
//         String body = await response.stream.bytesToString();
//         var jsonData = json.decode(body);
//         return jsonData['media_id']; // 关键参数，后续发送需使用
//       } else {
//         throw Exception('上传失败: HTTP ${response.statusCode}');
//       }
//     } catch (e) {
//       throw Exception('请求异常: $e');
//     }
//   }


// }



/// 企业微信机器人客户端（修正版）
class WeChatRobot {

  final String key='6072ed81-7294-48b5-a017-fc990e2ff40e';

  /// 发送文本消息
  Future<void> sendTextMessage(String content) async {
    final Map<String, dynamic> message = {
      "msgtype": "text",
      "text": {
        "content": content,
      },
    };

    final response = await http.post(
      Uri.parse('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}'),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode(message),
    );

    if (response.statusCode == 200) {
      print("消息发送成功: ${response.body}");
    } else {
      print("消息发送失败: ${response.statusCode}, ${response.body}");
    }
  }
  /// 上传文件到企业微信（返回media_id）
  Future<String> uploadFile(String filePath) async {
    final uploadUrl = Uri.parse(
      'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=$key&type=file'
    );

    final file = File(filePath);
    if (!await file.exists()) {
      throw Exception('文件不存在: $filePath');
    }

    final request = http.MultipartRequest('POST', uploadUrl)
      ..files.add(await http.MultipartFile.fromPath('media', filePath));

    try {
      final response = await request.send();
      final body = await response.stream.bytesToString();
      
      if (response.statusCode == 200) {
        return jsonDecode(body)['media_id'] as String;
      } else {
        throw Exception('上传失败: ${jsonDecode(body)['errmsg']}');
      }
    } catch (e) {
      throw Exception('上传请求异常: $e');
    }
  }

  /// 发送文件消息（使用类内webhookUrl）
  Future<bool> sendFile(String mediaId) async {
    try {
      final response = await http.post(
        Uri.parse('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          "msgtype": "file",
          "file": {"media_id": mediaId}
        }),
      );
      
      return response.statusCode == 200 && 
             jsonDecode(response.body)['errcode'] == 0;
    } catch (e) {
      return false;
    }
  }
}